<template>
  <st-dialog :title="title" v-if="open"
             height="650px"
             @close="cancel"
             @save="submitForm"

             append-to-body>
    <div v-loading="loading">
    <div class="container-top">
        <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-row>
        <el-col :span="11">
          <el-form-item label="关联合同：" prop="contractId">
            <el-input readonly v-model="form.contractName" placeholder="请选择合同">
                <el-button slot="append" @click="contractSelect" icon="el-icon-search"></el-button>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="提前几天提醒：" prop="remind">
            <el-select
              v-model="form.remind"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="dict in dict.type.receivables_plan_remind"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="11">
          <el-form-item label="合同金额：">
            <el-input :disabled="true" v-model="contractItem.money"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="11">
          <el-form-item label="合同类型：">
            <el-input :disabled="true" v-model="contractItem.typesDisp"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    </div>
    <div class="container-bottom" >
      <el-row>
        <el-col :span="9">
          <el-button type="primary" @click="addPlan">添加回款期数</el-button>
        </el-col >
      </el-row>

      <x-form ref="xForm" v-model="formData" :config="formConfig">
      </x-form>
    </div>
    <contract-select ref="contractSelect" @selected="contractSelected"></contract-select>
    </div>
  </st-dialog>
</template>
<script>
import  contractSelect from '@/views/crm/components/contractSelect.vue'
import {addPlan} from '@/api/crm/plan'
export default {
  components:{
    contractSelect
  },
  props:{
    customerForm:{
      type:Object,
      default:function() {
        return {};
      }
    }
  },
  dicts:['receivables_plan_returntype','receivables_plan_remind'],
  data() {
    return {
      loading:false,
      title:'',
      form:{},
      rules:{
        'contractId':[{ required: true, message: '请选择关联客户', trigger: ['blur', 'change'] }],
        'remind':[{ required: true, message: '请选择', trigger: ['blur', 'change'] }],
      },
      open:false,
      formData: {
        dataList: []
      },
      operateType:'',
      contractItem:{},
    }
  },
  watch:{
    'formData.dataList':{
      handler(newVal,oldVal){
        let salesPriceSum=0;
        let priceSum=1;
        this.formData.dataList.forEach((item)=>{
          salesPriceSum += item.salesPrice * item.num;
          priceSum=item.price * item.num;
        });
        console.log(salesPriceSum,priceSum);
        this.$set(this.form, 'discountRate',(salesPriceSum/priceSum).toFixed(2));
        this.$set(this.form, 'totalPrice',salesPriceSum);
        this.$set(this.form, 'money',priceSum);
        this.priceSum=salesPriceSum;
      },
      deep: true,
    },
  },
  computed: {
    formConfig() {
      const _this = this;
      const returntype =  this.dict.type.receivables_plan_returntype;
      return {
        inline: false,
        item: [
          {
            xType: 'table',
            table:{
              label: '回款期数列表',
              name: 'dataList',
              height: 'calc(100vh - 566px)',
              size: 'mini',
              operate: {
                show: true,
                label: '操作',
                width: '80px',
                headerAlign: 'center',
                align: 'center',
                btn: [
                  {
                    type: 'text',
                    text:'删除',
                    icon: 'el-icon-delete',
                    size: 'mini',
                    circle: true,
                    style: '',
                    className: '',
                    click:(arr, index) => {
                      _this._handleItem(arr, index)
                    }
                  }
                ]
              },
              column: [
                {
                  label: '期数',
                  name: 'num',
                  width: '80'
                },
                {
                  label: '回款方式',
                  name: 'returnType',
                  xType: 'select',
                  dic: returntype,
                },
                {
                  label: '回款日期',
                  name: 'returnDate',
                  xType: 'datePicker',
                  valueFormat:'yyyy-MM-dd'
                },
                {
                  label: '回款金额',
                  name: 'money',
                  xType: 'inputNumber',
                  rules: [{ required: true, message: '请输入金额', trigger: ['blur', 'change'] }]
                }
              ]
            }
          }
        ]
      }
    }
  },
  methods: {
    show(){
      this.reset();
      this.formData.dataList.splice(0,this.formData.dataList.length);
      this.open = true;
      this.loading=false;
      this.title='添加回款计划';
      this.operateType='add';
    },
    contractSelect(){
      this.$refs['contractSelect'].show();
    },
    // 表单重置
    reset() {
      this.form = {
        planId: null,
        num: null,
        receivablesId: null,
        contractId: null,
        customerId: null,
        status: null,
        money: null,
        returnDate: null,
        returnType: null,
        remind: null,
        remindDate: null,
        remark: null,
        createdBy: null,
        ownerUserId: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null
      };
      this.resetForm("form");
    },
    addPlan(){
      this.formData.dataList.push({
          'num': this.formData.dataList.length+1,
          'money':0,
          'returnDate':'',
          'returnType':'',
      })
    },
    contractSelected(item){
      this.contractItem=item;
      this.$set(this.form,'contractId',item.contractId);
      this.$set(this.form,'contractName',item.contractName);
      console.log(item);
    },
    _handleItem(arr, index){
      this.formData.dataList.splice(index,1);
    },
    cancel(){
      this.open=false;
    },
    submitForm(){
      this.$refs['form'].validate().then((valid, obj) => {
        if (valid) {
          this.$refs['xForm'].validate().then(() => {
            for(let item of this.formData.dataList){
              this.$set(item,'contractId',this.form.contractId);
              this.$set(item,'remind',this.form.remind);
              this.$set(item,'customerId',this.customerForm.customerId);
            }
            this.loading=true;
            addPlan(this.formData.dataList).then((res)=>{
              this.loading=false;
              this.open=false;
              this.$emit("list");
            });
          })
        }
      })

    },
  }
}
</script>
<style scoped lang="scss">
.el-form{
  padding: 10px 0 0 0;
}
.el-date-editor{
  width:100%;
}
.el-select{
  width: 100%;
}
</style>
